﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling.Diagrams;
using System.Drawing;
using System.Runtime.InteropServices;

namespace DSLFactory.VSCTDesigner
{
    internal static class ShapeHelper
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetDesktopWindow();
 
        public static void ShowHideChildren(NodeShape pel, bool flag)
        {
            Command grp = pel.Subject as Command;
            if( grp == null )
                return;

            foreach( var link in CommandHasParent.GetLinksToChilds(grp) )
            {
                foreach( BinaryLinkShape shape in PresentationViewsSubject.GetPresentation(link) )
                {
                    if( shape.ToShape == pel )
                    {
                        shape.FromShape.SetShowHideState(flag);
                        ShowHideChildren(shape.FromShape, flag);
                    }
                }
            }
        }

        #region Resize to content
        internal static void ResizeToContent(NodeShape shape)
        {
            double width = 0.27;
            Decorator decorator = shape.FindDecorator("NameDecorator");
            if( ( decorator != null ) && ( decorator.Field != null ) )
            {
                SizeD ed = MeasureDisplayText(decorator.Field.GetAccessibleValue(shape), ( (TextField)decorator.Field ).GetFont(shape), ( (TextField)decorator.Field ).GetStringFormat(shape));
                width += Math.Max(1.1, ed.Width);
                width += ( 0.05 + GetDecoratorWidth(shape, "ExpandCollapseDecorator") + GetDecoratorWidth(shape, "IconDecorator") + 0.08);
                shape.Size = new SizeD(width, shape.Size.Height);
            }
            shape.ConnectionPoints.Clear();
            shape.EnsureConnectionPoints(null);
        }

        private static SizeD MeasureDisplayText(string displayText, Font font, StringFormat format)
        {
            using( Graphics graphics = Graphics.FromHwnd(GetDesktopWindow()) )
            {
                SizeF ef = graphics.MeasureString(displayText, font, new SizeF(1000f, 1000f), format);
                return new SizeD((double)ef.Width, (double)ef.Height);
            }
        }

        private static double GetDecoratorWidth(NodeShape shape, string decoratorName)
        {
            Decorator decorator = shape.FindDecorator(decoratorName);
            if( ( decorator != null ) && ( decorator.Field != null ) )
            {
                return decorator.Field.GetBounds(shape).Width;
            }
            return 0.0;
        }

        #endregion
    }
}
